iT邦幫忙

第 11 屆 iThome 鐵人賽

DAY 5
0

JavaScript

JavaScript 的由來: Ref

學習使用 JavaScript (JS) 的時候,發現文件中基礎的很大一部分,都是對 API 的語法教學,自認為這種學習方法對於了解 JS 的幫助其實不大。與其直接看文件,不如直接看程式碼,如同學習英文一樣,看不懂的再翻文件的方式,認為是筆記好的學習方式。

學習/開發 環境

  1. Online: CodePen
  2. VsCode
    • Live Server
    • Eslint
    • 題外話: Visual Studio Code 也是用 JavaScript 完成的喔! (Help > Toggle Developer Tools)

學習資源

  1. MDN - JavaScript
  2. W3C School JavaScript

JS 學習閱讀範本

JS 範例: Matching Game

<html>
<head>
    <title>Matching Game</title>
    <style>
        img {
            position: absolute;
        }        
        div {
            position: absolute;
            width: 500px;
            height: 500px;
        }        
        #rightSide {
            left: 500px;
            border-left: 1px solid black
        }
    </style>
</head>
<body>
    <h1><a href="https://www.coursera.org/learn/html-css-javascript/peer/dwdxh/matching-game"> Matching Smile Game</a></h1>
    <nav>Click on the extra smiling face on the left.</nav>
    <main>
        <h2 id='docLevel'>Level 1 : </h2>
        <button id='start' onclick="startGame()">Start Game!</button>
        <button onclick='resetGame()'>Reset Game</button>
        <div id='playArea'>
            <div id="leftSide"></div>
            <div id="rightSide"></div>
        </div>
    </main>
    <script>
        var number_of_face = 4;
        var theLeftSide = document.getElementById('leftSide');
        var theRightSide = document.getElementById('rightSide');
        var leftSideImages;
        var extra_img;
        function generateFaces() {
            //left side            
            for (var i = 0; i < number_of_face; i++) {
                var smile_img;
                smile_img = document.createElement('img');
                smile_img.src = "smile.png";

                var top_position = Math.floor(Math.random() * 400) + 'px';
                var left_position = Math.floor(Math.random() * 400) + 'px';
                smile_img.style.top = top_position;
                smile_img.style.left = left_position;
                theLeftSide.appendChild(smile_img);
            }
            extra_img = theLeftSide.lastChild;
            // right side           
            leftSideImages = theLeftSide.cloneNode(true);
            leftSideImages.removeChild(leftSideImages.lastChild);
            theRightSide.appendChild(leftSideImages);
        }

        function addEvent() {
            extra_img.addEventListener('click', nextLevel);
            for (var i = 0; i < number_of_face - 1; i++) {
                theLeftSide.children[i].addEventListener('click', gameOver);
            }
        }

        function startGame() {
            removeFace();
            generateFaces();
            addEvent();
            document.getElementById('docLevel').textContent = "Level " + (number_of_face / 2 - 1) + ' : ' + (number_of_face - 1) + ' match Faces and 1 extra Face';
            document.getElementById('start').textContent = 'Try again! ';
        }

        function nextLevel(event) {
            event.stopPropagation();
            number_of_face += 2;
            removeFace();
            startGame();
        }

        function removeFace() {
            while (theLeftSide.firstChild) {
                theLeftSide.removeChild(theLeftSide.firstChild);
            }
            while (theRightSide.firstChild) {
                theRightSide.removeChild(theRightSide.firstChild);
            }
        }

        function resetGame() {
            number_of_face = 4;
            document.getElementById('start').textContent = 'Start Game! ';
            startGame();
        }

        var playArea = document.getElementById('playArea');

        function gameOver() {
            alert('Game over!');
            playArea.onclick = null;
            extra_img.onclick = null;
        }
    </script>
</body>
</html>

Guess Number

<html>
<head>
    <meta charset="utf-8">
    <title>Number guessing game</title>
    <style>
        html {
            font-family: sans-serif;
        }
        
        body {
            width: 50%;
            max-width: 800px;
            min-width: 480px;
            margin: 0 auto;
        }
        
        .lastResult {
            color: white;
            padding: 3px;
        }
    </style>
</head>
<body>
    <h1>Number guessing game</h1>
    <p>We have selected a random number between 1 and 100. See if you can guess it in 10 turns or fewer. We'll tell you if your guess was too high or too low.</p>
    <div class="form"> <label for="guessField">Enter a guess: </label><input type="text" id="guessField" class="guessField"> <input type="submit" value="Submit guess" class="guessSubmit"> </div>
    <div class="resultParas">
        <p class="guesses"></p>
        <p class="lastResult"></p>
        <p class="lowOrHi"></p>
    </div>
    <script>
        var random_number = Math.floor(Math.random() * 100 + 1);

        var guesses = document.querySelector('.guesses');
        var lastResult = document.querySelector('.lastResult');
        var lowOrHi = document.querySelector('.lowOrHi');

        var guessSubmit = document.querySelector('.guessSubmit');
        var guessField = document.querySelector('.guessField');

        var guessCount = 1;
        var resetButton;

        function checkGuess() {
            var userGuess = Number(guessField.value);
            if (guessCount === 1) {
                guesses.textContent = 'Previous guesses: ';
            }
            guesses.textContent += userGuess + ', ';

            if (userGuess === random_number) {
                lastResult.textContent = 'Congratulations! You got it right!';
                lastResult.style.backgroundColor = 'green';
                lowOrHi.textContent = '';
                setGame_Over();
            } else if (guessCount === 10) {
                lastResult.textContent = ' GAME OVER !!!';
                lowOrHi.textContent = '';
                setGame_Over();
            } else {
                lastResult.textContent = 'WRONG! ';
                lastResult.style.backgroundColor = 'red';
                if (userGuess > random_number) {
                    lowOrHi.textContent = 'Too High';
                } else {
                    lowOrHi.textContent = 'Too Low';
                }

            }
            guessCount++;
            guessField.value = '';
            guessField.focus();

        }

        guessSubmit.addEventListener('click', checkGuess);

        function setGame_Over() {
            guessField.disabled = true;
            guessSubmit.disabled = true;
            resetButton = document.createElement('button');
            resetButton.textContent = 'Start new game';
            document.body.appendChild(resetButton);
            resetButton.addEventListener('click', resetGame);
        }

        function resetGame() {
            guessCount = 1;

            var resetParas = document.querySelectorAll('.resultParas p');
            for (var i = 0; i < resetParas.length; i++) {
                resetParas[i].textContent = '';
            }

            resetButton.parentNode.removeChild(resetButton);
            guessField.disabled = false;
            guessSubmit.disabled = false;
            guessField.value = '';
            guesses.focus();

            lastResult.style.backgroundColor = 'white';

            random_number = Math.floor(Math.random() * 100 + 1);
        }
    </script>
</body>
</html>
<!-- https://developer.mozilla.org/en-US/docs/Learn/JavaScript/First_steps/A_first_splash -->**

JS-Adding_features_to_our_bouncing_balls_demo

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>Bouncing balls</title>
    <link rel="stylesheet" href="style.css">
</head>
<body>
    <h1><a href="https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Objects/Adding_bouncing_balls_features" target="_blank">bouncing balls</a></h1>
    <p></p>
    <canvas></canvas>
    <script src="main-finished.js"></script>
</body>
</html>
// setup canvas

var canvas = document.querySelector('canvas');
var ctx = canvas.getContext('2d');

var width = canvas.width = window.innerWidth;
var height = canvas.height = window.innerHeight;

var ballCount = document.querySelector('p');
var count = 0;



// function to generate random number

function random(min, max) {
    var num = Math.floor(Math.random() * (max - min)) + min;
    return num;
}

// define Ball constructor

function Shape(x, y, velX, velY, exists) {
    this.x = x;
    this.y = y;
    this.velX = velX;
    this.velY = velY;
    this.exists = exists;
}

function Ball(x, y, velX, velY, exists, color, size) {
    Shape.call(this, x, y, velX, velY, exists);
    this.color = color;
    this.size = size;
    this.exists = exists;
}


Ball.prototype = Object.create(Shape.prototype);
Ball.prototype.constructor = Ball;


// define ball draw method

Ball.prototype.draw = function() {
    ctx.beginPath();
    ctx.fillStyle = this.color;
    ctx.arc(this.x, this.y, this.size, 0, 2 * Math.PI);
    ctx.fill();
};

// define ball update method

Ball.prototype.update = function() {
    if ((this.x + this.size) >= width) {
        this.velX = -(this.velX);
    }

    if ((this.x - this.size) <= 0) {
        this.velX = -(this.velX);
    }

    if ((this.y + this.size) >= height) {
        this.velY = -(this.velY);
    }

    if ((this.y - this.size) <= 0) {
        this.velY = -(this.velY);
    }

    this.x += this.velX;
    this.y += this.velY;
};

// define ball collision detection

Ball.prototype.collisionDetect = function() {
    for (var j = 0; j < balls.length; j++) {
        if (!(this === balls[j])) {
            var dx = this.x - balls[j].x;
            var dy = this.y - balls[j].y;
            var distance = Math.sqrt(dx * dx + dy * dy);

            if (distance < this.size + balls[j].size) {
                balls[j].color = this.color = 'rgb(' + random(0, 255) + ',' + random(0, 255) + ',' + random(0, 255) + ')';
            }
        }
    }
};

//Difining EvilCircle()
function EvilCircle(x, y, velX, VelY, exists) {
    Shape.call(this, x, y, velX, VelY, exists);

    this.color = 'white';
    this.size = 50;
    this.exists = true;
}

EvilCircle.prototype = Object.create(Shape.prototype);
EvilCircle.prototype.constructor = EvilCircle;

EvilCircle.prototype.draw = function() {
    ctx.beginPath();
    ctx.lineWidth = 3;
    ctx.strokeStyle = this.color;
    ctx.arc(this.x, this.y, this.size, 0, 2 * Math.PI);
    ctx.stroke();
};

EvilCircle.prototype.checkBounds = function() {
    if ((this.x + this.size) >= width) {
        //this.velX = -(this.velX);
        this.x = width - (this.size * 2);
    }

    if ((this.x - this.size) <= 0) {
        //this.velX = -(this.velX);
        this.x = this.size * 2;
    }

    if ((this.y + this.size) >= height) {
        //this.velY = -(this.velY);
        this.y = height - (this.size * 2);
    }

    if ((this.y - this.size) <= 0) {
        //this.velY = -(this.velY);
        this.y = this.size * 2;
    }
};

EvilCircle.prototype.setControl = function() {
    // Why need this
    var _this = this;
    window.onkeydown = function(e) {
        if (e.keyCode === 65) {
            _this.x -= _this.velX;
        } else if (e.keyCode === 68) {
            _this.x += _this.velX;
        } else if (e.keyCode === 87) {
            _this.y -= _this.velY;
        } else if (e.keyCode === 83) {
            _this.y += _this.velY;
        }
    }
};

EvilCircle.prototype.collisionDetect = function() {
    for (var j = 0; j < balls.length; j++) {
        if (balls[j].exists == true) {
            var dx = this.x - balls[j].x;
            var dy = this.y - balls[j].y;
            var distance = Math.sqrt(dx * dx + dy * dy);

            if (distance < this.size + balls[j].size) {
                balls[j].exists = false;
                count += 1;
                ballCount.innerHTML = 'Balls Counts : ' + (balls.length - count);
            }

        }

    }
};

// define array to store balls

var balls = [];
var evilBall = new EvilCircle(50, 50, 20, 20, true);

// define loop that keeps drawing the scene constantly

function loop() {
    ctx.fillStyle = 'rgba(0,0,0,0.25)';
    ctx.fillRect(0, 0, width, height);
    evilBall.setControl();

    while (balls.length < 25) {
        var ball = new Ball(
            random(0, width),
            random(0, height),
            random(-7, 7),
            random(-7, 7),
            true,
            'rgb(' + random(0, 255) + ',' + random(0, 255) + ',' + random(0, 255) + ')',
            random(10, 20),
        );
        balls.push(ball);
    }

    for (var i = 0; i < balls.length; i++) {
        if (balls[i].exists) {
            balls[i].draw();
            balls[i].update();
            balls[i].collisionDetect();
        }
    }
    evilBall.draw();
    evilBall.checkBounds();
    evilBall.collisionDetect();


    requestAnimationFrame(loop);
}

loop();

上一篇
版本控制系統
下一篇
JavaScript Library: jQuery
系列文
網頁服務開發之路30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言